package cn.ges.spring;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;

import java.util.Map;

/**
 * @author gespent@163.com
 * @date 2019/4/26
 */
public class SpringContextUtil {

    private static ApplicationContext applicationContext;
    private static DefaultListableBeanFactory defaultListableBeanFactory;

    /**
     * 初始化方法
     */
    public static void initSpringContextUtil(ApplicationContext applicationContext, DefaultListableBeanFactory defaultListableBeanFactory) {

        SpringContextUtil.applicationContext = applicationContext;
        SpringContextUtil.defaultListableBeanFactory = defaultListableBeanFactory;

    }

    public static void setSpringContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public SpringContextUtil(ApplicationContext applicationContext) throws BeansException {
        // spring初始化该类时 将注入 applicationContext
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static void registerSingleton(String beanName, Object singletonBean) {
        //让obj完成Spring初始化过程中所有增强器检验，只是不重新创建obj，
        applicationContext
                .getAutowireCapableBeanFactory()
                .applyBeanPostProcessorsAfterInitialization(singletonBean, singletonBean.getClass().getName());
        //将obj以单例的形式入驻到容器中，此时通过obj.getClass().getName()或obj.getClass()都可以拿到放入Spring容器的Bean。
        defaultListableBeanFactory.registerSingleton(beanName, singletonBean);
    }


    /**
     * 获取applicationContext对象
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据bean的id来查找对象
     */
    public static Object getBeanById(String id) {
        return applicationContext.getBean(id);
    }

    /**
     * 根据bean的class来查找对象
     */
    public static <T> T getBeanByClass(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     */
    public static <T> Map<String, T> getBeansByClass(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }
}
